'use strict'
var mongoose = require('mongoose')
var Staff = mongoose.model('staff')
var uuid = require('uuid')

exports.inquire = async (ctx, next) => {
  var offset = parseInt(ctx.query.offset) || 0
  var count = parseInt(ctx.query.limit) || 5
  var queryArray = await Staff.find()
      .sort({
        'createAt': -1
      })
      .skip(offset)
      .limit(count);
  var total = await Staff.estimatedDocumentCount()
  ctx.body = {
    success: true,
    objects: queryArray,
    meta: {
      total_count: total
    }
  }
}
exports.add = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var stSerial = 'EM-'+uuid.v4();
    var data = new Staff({
      stSerial: stSerial,
      nativePlace: body.nativePlace,
      department: body.department,
      name: body.name,
      gender: body.gender,
      post: body.post,
      status: body.status,
      avatar: body.avatar || '',
      birthday: body.birthday,
      marriage: body.marriage,
      education: body.education,
      salary: body.salary,
      phoneNumber: body.phoneNumber,
      address: body.address
    });
    data.save();
    ctx.body = {
      success: true,
      message: '添加成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.update = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var msg = await Staff.findByIdAndUpdate(body._id, {
      nativePlace: body.nativePlace,
      department: body.department,
      name: body.name,
      gender: body.gender,
      post: body.post,
      status: body.status,
      avatar: body.avatar,
      birthday: body.birthday,
      marriage: body.marriage,
      education: body.education,
      salary: body.salary,
      phoneNumber: body.phoneNumber,
      address: body.address
    })
    ctx.body = {
      success: true,
      message: '编辑成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.remove = async (ctx, next) => {
  try {
    var id = ctx.query && ctx.query.id
    if(id) {
      // var Staff = await Staff.findById(id);
      var msg = Staff.findOneAndRemove({_id: id}).exec();
      if(msg){
        ctx.body = {
          success: true,
          message: '删除成功'
        }
      }else{
        ctx.body = {
          success: false,
          message: '没有该员工！'
        }
      }
    }
  } catch (error) {
    console.log('删除失败');
  }
}